#include "messages.h"

struct mq_node *create_node(int id, int kind, int lc)
{
    struct mq_node *newNode = (struct mq_node *)calloc(1, sizeof(struct mq_node));
    newNode->id = id;
    newNode->kind = kind;
    newNode->lc = lc;
    newNode->ack = 0;
    newNode->next = NULL;
    return newNode;
}

void insertNode(struct mq_node *newNode)
{    
    //se é o primeiro, coloca no início da fila
    if(mqueue == NULL)
    {
        mqueue = newNode;
    }
    //se a fila tem tamanho == 1, verifica se vai antes ou depois
    else if(mqueue->next == NULL)
    {
        if(newNode->lc < mqueue->lc || (newNode->lc == mqueue->lc && newNode->id < mqueue->id))
        {
            newNode->next = mqueue;
            mqueue = newNode;
        }
        else
        {
            mqueue->next = newNode;
        }
    }
    else if(newNode->lc < mqueue->lc || (newNode->lc == mqueue->lc && newNode->id < mqueue->id))
    {
        newNode->next = mqueue;
        mqueue = newNode;
    }
    //se a fila tem tamanho >= 2, itera por seus elementos
    else
    {
        struct mq_node *iterator = mqueue;
        while(1)
        {
            if(iterator->next != NULL)
            {
                if(newNode->lc < iterator->next->lc || (newNode->lc == iterator->next->lc && newNode->id < iterator->next->id))
                {
                    newNode->next = iterator->next;
                    iterator->next = newNode;
                    break;
                }
                else
                {
                    iterator = iterator->next;
                }
            }
            else
            {
                iterator->next = newNode;
                break;
            }
        }
    }
}

    

void ackNode(int id, int lc)
{
    struct mq_node *iterator = mqueue;
    while(iterator)
    {
        if(iterator->id == id && iterator->lc == lc)
        {
            iterator->ack++;
            exit(0);
        }
    }
    printf("Received ack for nonexistent message! %d, %d\n", id, lc);
}
void printList()
{
    printf("\n\nImprimindo lista:\n\n");
    struct mq_node *iterator = mqueue;
    while(iterator != NULL)
    {
        printf("ID: %d, lc: %d\n", iterator->id, iterator->lc);
        iterator = iterator->next;
    }
}
//TODO Inserir na lista ordenadamente, adicionar acks na lista

